<?php

namespace app\api\controller\weike;

use app\common\controller\Api;
use think\Config;
use think\Db;

/**
 * 微客社区课程
 */
class Index extends Api
{
    protected $noNeedLogin = ['category','forumList','statistics'];
    protected $noNeedRight = ['forumCreate','forumlike','forumevaluate'];


    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }
        $this->forumcategory=model('admin/weike/Forumcategory');
        $this->forum=model('admin/weike/Forum');
        $this->forumgoods=model('admin/weike/Forumgoods');
        $this->forumlike=model('admin/weike/Forumlike');
        $this->forumevaluate=model('admin/weike/Forumevaluate');
        $this->user=model('admin/User');


    }

    /**
     * 课程分类
     * @param int $pid
     */
    public function category($pid=null){
        $where=[];
        if($pid!=null){
            $where['pid']=['=',$pid];
        }
     //  dump($where);
        $this->success('OK',$this->forumcategory->where($where)->order('weigh desc')->select());
    }

    /**
     * 发布论坛
     * @param $top_id
     * @param int $two_id
     * @param $content
     * @param null $images
     * @param string $is_shop
     * @param string $goods
     * @throws \think\exception\PDOException
     */
     public  function  forumCreate($top_id,$two_id=0,$content,$images=null,$is_shop='否',$goods=''){
         $forumdata=['top_id'=>$top_id,
                'two_id'=>$two_id,
                 'content'=>$content,
                  'images'=>$images,
                 'user_id'=>$this->auth->id,
                 'is_shop'=>$is_shop
             ];
         try{
         db()->startTrans();

        $r= $this->forum::Create($forumdata);

            if($this->auth->is_forum=='否'){
                $this->user->where('id',$this->auth->id)->update(['is_forum'=>'是']);
            }

        if($is_shop=='是' ){
           if($goods=='') $this->error('选择发布商品，商品信息不能为空');
            $goods= json_decode(html_entity_decode($goods),true) ;
            $alldata=[];
            foreach($goods as $key=>$value){
                $data=['goods_name'=>$value['goods_name'],
                    'images'=>$value['images'],
                    'price'=>$value['price'],
                    'weike_forum_id'=>$r->id,
                    'user_id'=>$this->auth->id,
                ];
                $alldata[]=$data;
            }
            $this->forumgoods->SaveAll($alldata);
        }

         db()->commit();

                 $this->success('发布成功');
             }catch (Exception $e){
        db()->rollback();
        $this->error($e->getMessage()?:'系统错误');
           }

     }

    /**
     * 论坛点赞
     * @param $id
     */
     public function forumlike($id,$type='点赞'){
        // exit;
         $forum= $this->forum->get($id);
         if($forum){
              if($type=='点赞'){
                  if($this->forumlike->get(['user_id'=>$this->auth->id,'weike_forum_id'=>$id])) $this->error('您已点赞');
                  $this->forumlike::Create(['user_id'=>$this->auth->id,'weike_forum_id'=>$id]);
                  $forum->setInc('like',1);
              }
              if($type=='取消点赞'){
                  if(!$forumlike=$this->forumlike->get(['user_id'=>$this->auth->id,'weike_forum_id'=>$id])) $this->error('您还未点赞');
                  $this->forumlike->where(['user_id'=>$this->auth->id,'weike_forum_id'=>$id])->delete();
                  $forum->setDec('like',1);
              }

             if($this->auth->is_forum=='否'){
               $this->user->where('id',$this->auth->id)->update(['is_forum'=>'是']);
             }
             $this->success($type.'成功');

         }else{
             $this->error('贴子未找到');
         }

     }

    /**
     * 论坛评论
     * @param $id
     * @param $evaluate
     */
     public function forumevaluate($id,$evaluate,$images=null){

          if($evaluate=='')   $this->error('评论内容不能为空');
         $forum= $this->forum->get($id);
         if($forum){
           $this->forumevaluate::Create(['weike_forum_id'=>$id,'evaluate'=>$evaluate,'user_id'=>$this->auth->id,'images'=>$images]);
             $forum->setInc('evaluate',1);

             if($this->auth->is_forum=='否'){
                 $this->user->where('id',$this->auth->id)->update(['is_forum'=>'是']);
             }
             $this->success('评论成功');

         }else{
             $this->error('贴子未找到');
         }
     }

    /**帖子列表
     * @param int $page
     * @param int $limit
     * @param int $top_id
     * @param int $two_id
     * @param null $keywords
     */
      public function forumList($page=1,$limit=10,$top_id=0,$two_id=0,$keywords=null){

        $where=[];
          $where['f.status']=['=','normal'];
        if($top_id!=0){
            $where['f.top_id']=['=',$top_id];
        }
          if($two_id!=0){
              $where['f.two_id']=['=',$two_id];
          }
          if($keywords!=null){
              $where['f.content']=['like',"%".$keywords."%"];
          }


         $forumList= $this->forum
              ->alias('f')
              ->join('__USER__ u ','f.user_id= u.id')
              ->where($where)
              ->order('f.createtime desc')
              ->field('f.*,u.username,u.avatar,u.nickname')
              ->paginate($limit);
           foreach ($forumList as $key=>$value){
               $forumList[$key]['createtime']=date('Y-m-d H:i:s',$value['createtime']);
               $forumList[$key]['images']=explode(",",$value['images']);
               if($value['is_shop']=='是'){
                  $forumgoods= $this->forumgoods->where('weike_forum_id',$value['id'])->select();
                   foreach ($forumgoods as $k=>$v){
                       $forumgoods[$k]['images']=explode(",",$v['images']);
                   }
                   $forumList[$key]['goodsList']=$forumgoods;
               }
             $forumevaluate= $this->forumevaluate->where('weike_forum_id',$value['id'])->select();
               foreach ($forumevaluate as $ko=>$vo){
                   $forumevaluate[$ko]['images']=explode(",",$vo['images']);
                   $forumevaluate[$ko]['createtime']=date('Y-m-d H:i:s',$vo['createtime']);
               }

               //用户是否点赞

               if($this->forumlike->get(['user_id'=>$this->auth->id,'weike_forum_id'=>$value['id']])){
                   $forumList[$key]['is_like']=1;
               }else{
                   $forumList[$key]['is_like']=0;
               }

               $forumList[$key]['forumevaluate']=$forumevaluate;

           }
           $this->success('ok',$forumList);

      }

    /**
     * 微客统计
     */
    public function statistics(){


              $data['dynamic']= Config('site.weike_all_dongtai')+$this->forum->where('status','normal')->count();

               $data['todaydynamic']=Config('site.weike_today_dongtai')+$this->forum->where('status','normal')->where('createtime','in',[strtotime(date('Y-m-d',time()),time())])->count();

               $data['userforum']=Config('site.ruzhu_user')+ $this->user->where('is_forum','是')->count();

               $this->success('OK',$data);
    }

}
